According to Centers for Disease Control and Prevention, in 2015-2016, more than 12% of adults at the age of 20 and above in the United States have cholesterol levels higher than 240mg/ml. A high cholesterol level is one of the major risk factors for coronary heart disease, heart attack and stroke. While there are two types of cholesterol, low-density lipoprotein (LDL) is known as the “bad” one that leads to the buildup of cholesterol in arteries. The goal of this project is to explore factors that can affect the level of LDL in a human body, and the result is intended to help readers gain insights on how to balance the level of LDL in order to control/prevent cardiovascular diseases.
The analysis result shows that age, weight, height, BMI, systolic and diastolic blood pressures, and the level of triglyceride are factors that can explain the variation in the level of LDL.
The data analysis is performed with the NHANES 2015-2016 data. The dependent variable, the level of low-density lipoprotein (LDL), measured by mg/dl, is selected from the dataset Cholesterol - LDL & Triglycerides of the laboratory data. Since a high level of triglyceride is believed to be associated with a high level of LDL, it is included in the model as the independent variable. Triglyceride data is also obtained from Cholesterol - LDL & Triglycerides of the laboratory data. We also include blood pressure readings from Blood Pressure dataset of the examination data. According to the data description, some participants have multiple blood pressure readings. For simplicity, we use averaged systolic and diastolic blood pressure readings as blood pressure measurements for each individual. Averaged intakes of fat and cholesterol, computed using both the First and the Second Day Total Nutrient Intakes of the dietary data, are added as independent variables as well. To account for more individual differences, we also include gender, race and age from the Demographics Data, and height, weight and BMI information from Body Measures of the examination data as additional covariates. Furthermore, SEQN, the respondent sequence number, is utilized as the unique identifier to match responses for each respondent. Finally, we removed all rows containing missing values, and there are a total of 2503 observations available for further analysis.
We fit models using multiple linear regression techniques and then perform model selections to choose the model that best describes the level of LDL. For the very first model, we regress the dependent variable LDL on all predictors:
\(\mathbf{LDL}\) ~ \(\mathbf{age + race + gender + height + weight + BMI + fat + cholesterol + triglyceride + diastolic + systolic}\) (1)
Note that covariates gender and race are treated as categorical variables.
A check of the relationship between residuals and fitted values suggests a transformation for the dependent variable.
Residual plot of the full model
With the help of the Box-Cox test:
Box-Cox Transformation plot
we identify that the square root transformation is the best choice.
We then fit a new linear model with the transformed dependent variable, \(\sqrt{LDL}\):
\(\mathbf{\sqrt{LDL}}\) ~ \(\mathbf{age + race + gender + height + weight + BMI + fat + cholesterol + triglycerides + diastolic + systolic}\) (2)
As the model has as many as 11 covariates and some of them are insignificant under t-test, we then use the stepwise selection technique to choose variables that best explain \(\sqrt{LDL}\).
Besides, we consider transformations upon predictors. Considering partial residual plots:
Partial Residual Plot
we find out that variables age and triglycerides violate the linear structure assumption. Both of these plots exhibit a quadratic form, so in addition to response variables in the full model (2) above, we add age2 and triglycerides2 to the linear regression model:
\(\mathbf{\sqrt{LDL}}\) ~ \(\mathbf{age + age^2 + race + gender + height + weight + BMI + fat + cholesterol + triglycerides + triglycerides^2 + diastolic + systolic}\) (3)
Just as the process before, we will execute the stepwise model selection technique to choose the most significant variables of this model.
Steps outlined above are carried out in R, Stata and Python. In R, we use the package data.table for data cleaning.
## Group Project HTML
## Author: Huayu Li, huayuli@umich.edu
## Updated: Dec. 8 2019
#### Data cleaning using data.table
## Libraries: -------------------------------------------------------------------------
library(data.table)
library(foreign)
library(tidyverse)
## 80: --------------------------------------------------------------------------------
## Read the datasets
demo=data.table(read.xport("./Original Data/DEMO_I.XPT.txt"))
tot1=data.table(read.xport("./Original Data/DR1TOT_I.XPT.txt"))
tot2=data.table(read.xport("./Original Data/DR2TOT_I.XPT.txt"))
b_pres=data.table(read.xport("./Original Data/BPX_I.XPT.txt"))
ldl=data.table(read.xport("./Original Data/TRIGLY_I.XPT.txt"))
measure=data.table(read.xport("./Original Data/BMX_I.XPT.txt"))
## For each dataset, choose the proper variables and make
## some transformation.
# For demo dataset, we choose seqn, gender, age and race variables
Demo=demo[,.(seqn=SEQN,gender=as.factor(RIAGENDR),
age=RIDAGEYR,race=as.factor(RIDRETH3))]
# For dietary data, we choose seqn, intake fat, intake cholesterol
# for each day.
TOT1=tot1[,.(seqn=SEQN,intake_fat1=DR1TTFAT,
intake_chol1=DR1TCHOL)]
TOT2=tot2[,.(seqn=SEQN,intake_fat2=DR2TTFAT,
intake_chol2=DR2TCHOL)]
## Next we will use the average intake of the two days into
## our model. The average step is as following:
intake_type=c('intake_fat1','intake_fat2','intake_chol1','intake_chol2')
TOT=TOT1%>%merge(.,TOT2,by='seqn',all=FALSE)
TOT=melt(TOT,measure=intake_type)[
,.(seqn,type=factor(variable,intake_type,c(rep('intake_fat',times=2),
rep('intake_chol',times=2))),
variable,value)
][
,.(intake=mean(value,na.rm=TRUE)),by=.(seqn,type)
]
TOT=dcast(TOT,...~type,value.var=c('intake'))
# For blood pressure, we choose seqn, systolic pressures and diastolic
# pressures. We then use the average pressure as the final pressure.
pres_type=c(paste('sys',1:4,sep=''),paste('dia',1:4,sep=''))
B_pres=b_pres[,.(seqn=SEQN,sys1=BPXSY1,sys2=BPXSY2,sys3=BPXSY3,sys4=BPXSY4,
dia1=BPXDI1,dia2=BPXDI2,dia3=BPXDI3,dia4=BPXDI4)]
B_pres=melt(B_pres,measure=pres_type)[,
.(seqn,type=factor(variable,pres_type,
c(rep('s',times=4),rep('d',times=4))),
variable,pressure=value)
][
,.(pres=mean(pressure,na.rm=TRUE)),by=.(seqn,type)
]
B_pres=dcast(B_pres,...~type,value.var=c('pres'))[
,.(seqn,systolic=s,diastolic=d)
]
# For ldl dataset, we choose seqn, LDL-cholesterol and Triglyceride
# for mg/dL.
LDL=ldl[,.(seqn=SEQN,ldl=LBDLDL,triglycerides=LBXTR)]
# For body measure dataset, we choose weight height and bmi as our
# variables.
Measure=measure[,.(seqn=SEQN,weight=BMXWT,height=BMXHT,bmi=BMXBMI)]
## Now merge the datasets into one whole, with the seqn as
## the merging label. By the way, some seqn labels
## should be removed, for they are not included in LDL dataset.
Data=Demo%>%merge(.,TOT,by='seqn',all=FALSE)%>%
merge(.,B_pres,by='seqn',all=FALSE)%>%
merge(.,LDL,by='seqn',all=FALSE)%>%
merge(.,Measure,by='seqn',all=FALSE)%>%
na.omit()
### Using this file for regression: ---------------------------------------------------
## Libraries: -------------------------------------------------------------------------
library(lme4)
library(MASS)
library(car)
## 80: --------------------------------------------------------------------------------
## Remove the seqn variable, and set gender and race as factor variables
DT=Data[,.(gender=as.factor(gender),age,race=as.factor(race),intake_fat,intake_chol,
systolic,diastolic,ldl,triglycerides,weight,height,bmi)]
## First of all, we will fit the model with all variables, and then give
## the residual plot of the model.
L1=lm(ldl~.,data=DT)
summary(L1)
##
## Call:
## lm(formula = ldl ~ ., data = DT)
##
## Residuals:
## Min 1Q Median 3Q Max
## -113.646 -22.757 -2.451 19.297 149.850
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 101.571467 44.874374 2.263 0.0237 *
## gender2 1.171152 1.847729 0.634 0.5262
## age 0.175782 0.038684 4.544 5.78e-06 ***
## race2 3.952555 2.414177 1.637 0.1017
## race3 2.036991 2.093998 0.973 0.3308
## race4 3.506045 2.285949 1.534 0.1252
## race6 5.104577 2.738375 1.864 0.0624 .
## race7 6.036927 3.880265 1.556 0.1199
## intake_fat 0.005288 0.022726 0.233 0.8160
## intake_chol -0.001265 0.004397 -0.288 0.7736
## systolic -0.005915 0.045972 -0.129 0.8976
## diastolic 0.401837 0.057452 6.994 3.41e-12 ***
## triglycerides 0.142759 0.011379 12.546 < 2e-16 ***
## weight 0.301651 0.266228 1.133 0.2573
## height -0.318111 0.269684 -1.180 0.2383
## bmi -0.595490 0.741391 -0.803 0.4219
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 33.34 on 2487 degrees of freedom
## Multiple R-squared: 0.1342, Adjusted R-squared: 0.129
## F-statistic: 25.69 on 15 and 2487 DF, p-value: < 2.2e-16
## Here we give the residual plot of the model
plot(L1$fitted.values,L1$residuals)
## Here, it seems that some transformations should be used upon ldl. Here
## we do the Box-Cox test.
boxcox(L1,plotit=TRUE,lambda=seq(0,1,1/100))
## Here it seems that lambda=0.5 is the best choice, that is, to use sqrt(ldl).
## Here we make the transformation and then do the regression again.
L2=lm(sqrt(ldl)~.,data=DT)
summary(L2)
##
## Call:
## lm(formula = sqrt(ldl) ~ ., data = DT)
##
## Residuals:
## Min 1Q Median 3Q Max
## -6.1905 -1.0601 0.0021 1.0178 5.5148
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.005e+01 2.158e+00 4.658 3.36e-06 ***
## gender2 5.965e-02 8.886e-02 0.671 0.5021
## age 8.429e-03 1.860e-03 4.531 6.15e-06 ***
## race2 1.830e-01 1.161e-01 1.576 0.1151
## race3 8.270e-02 1.007e-01 0.821 0.4116
## race4 1.305e-01 1.099e-01 1.187 0.2354
## race6 2.302e-01 1.317e-01 1.748 0.0806 .
## race7 2.744e-01 1.866e-01 1.470 0.1416
## intake_fat 4.259e-04 1.093e-03 0.390 0.6968
## intake_chol -8.613e-05 2.115e-04 -0.407 0.6838
## systolic -3.532e-04 2.211e-03 -0.160 0.8731
## diastolic 2.006e-02 2.763e-03 7.261 5.11e-13 ***
## triglycerides 6.538e-03 5.472e-04 11.948 < 2e-16 ***
## weight 1.492e-02 1.280e-02 1.165 0.2440
## height -1.644e-02 1.297e-02 -1.268 0.2050
## bmi -2.700e-02 3.566e-02 -0.757 0.4489
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.604 on 2487 degrees of freedom
## Multiple R-squared: 0.1327, Adjusted R-squared: 0.1275
## F-statistic: 25.38 on 15 and 2487 DF, p-value: < 2.2e-16
## There are too many variables in the regression model, so here we will do
## the model selection and choose the variables. Here we do both the forward
## and backward selections.
L3=step(L2,direction='both',trace=FALSE)
summary(L3)
##
## Call:
## lm(formula = sqrt(ldl) ~ age + diastolic + triglycerides + weight +
## height, data = DT)
##
## Residuals:
## Min 1Q Median 3Q Max
## -6.2425 -1.0646 0.0056 1.0406 5.5286
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 8.8488834 0.5771649 15.332 < 2e-16 ***
## age 0.0079968 0.0016065 4.978 6.87e-07 ***
## diastolic 0.0203065 0.0025879 7.847 6.28e-15 ***
## triglycerides 0.0064965 0.0005279 12.306 < 2e-16 ***
## weight 0.0049061 0.0017000 2.886 0.00394 **
## height -0.0083689 0.0036375 -2.301 0.02149 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.603 on 2497 degrees of freedom
## Multiple R-squared: 0.1304, Adjusted R-squared: 0.1286
## F-statistic: 74.87 on 5 and 2497 DF, p-value: < 2.2e-16
From the output result, we find out that variables age, diastolic, triglycerides, weight, height are selected, and they are all significant under t-test.
In this model, variables age, diastolic, triglycerides and weight are positive correlated to the fitted level of ldl, while height is negative correlated: with other variables fixed, one year of age increase leads to 0.008 unit increase in \(\sqrt{ldl}\), and 1 unit diastolic increase leads to 0.02 unit increase in \(\sqrt{ldl}\); 1 unit increase in triglycerides leads to 0.006 unit increase in \(\sqrt{ldl}\), and for weight this will lead to 0.005 unit increase in \(\sqrt{ldl}\); for height, this will lead to 0.008 unit decrease in \(\sqrt{ldl}\). The \(R^2\) is 0.1304, and the residual standard error is 1.603.
## By the way, in the models before, we didn't consider transformations
## upon predictors; in the coming part, we will consider adding some
## nonlinear terms.
crPlots(L2,layout=c(4,3))
## From the partial residual plots, we can find out that for triglycerides and age,
## some nonlinear transformation forms should be add. We add this term, and the
## regression result is as following:
L4=lm(sqrt(ldl)~gender+age+race+intake_fat+intake_chol+systolic+diastolic+
weight+height+bmi+triglycerides+I(triglycerides^2)+I(age^2),data=DT)
summary(L4)
##
## Call:
## lm(formula = sqrt(ldl) ~ gender + age + race + intake_fat + intake_chol +
## systolic + diastolic + weight + height + bmi + triglycerides +
## I(triglycerides^2) + I(age^2), data = DT)
##
## Residuals:
## Min 1Q Median 3Q Max
## -5.2795 -0.9630 -0.0056 0.9958 5.4639
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.155e+01 2.065e+00 5.593 2.47e-08 ***
## gender2 -7.780e-02 8.572e-02 -0.908 0.36421
## age 1.075e-01 8.753e-03 12.282 < 2e-16 ***
## race2 8.510e-02 1.109e-01 0.767 0.44310
## race3 1.954e-01 9.673e-02 2.020 0.04349 *
## race4 2.324e-01 1.053e-01 2.207 0.02739 *
## race6 1.303e-01 1.258e-01 1.035 0.30054
## race7 3.578e-01 1.782e-01 2.008 0.04472 *
## intake_fat -7.455e-05 1.043e-03 -0.071 0.94303
## intake_chol -1.705e-04 2.019e-04 -0.844 0.39857
## systolic 3.840e-03 2.141e-03 1.794 0.07298 .
## diastolic 6.303e-03 2.858e-03 2.206 0.02750 *
## weight 2.520e-02 1.223e-02 2.060 0.03950 *
## height -3.457e-02 1.246e-02 -2.775 0.00556 **
## bmi -7.122e-02 3.413e-02 -2.087 0.03703 *
## triglycerides 2.150e-02 1.660e-03 12.953 < 2e-16 ***
## I(triglycerides^2) -5.019e-05 5.005e-06 -10.027 < 2e-16 ***
## I(age^2) -1.138e-03 9.593e-05 -11.862 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.53 on 2485 degrees of freedom
## Multiple R-squared: 0.2114, Adjusted R-squared: 0.206
## F-statistic: 39.2 on 17 and 2485 DF, p-value: < 2.2e-16
## Just the same, do the model selection.
L5=step(L4,direction='both',trace=FALSE)
summary(L5)
##
## Call:
## lm(formula = sqrt(ldl) ~ age + systolic + diastolic + weight +
## height + bmi + triglycerides + I(triglycerides^2) + I(age^2),
## data = DT)
##
## Residuals:
## Min 1Q Median 3Q Max
## -5.2347 -0.9663 -0.0208 1.0166 5.4756
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 1.109e+01 2.011e+00 5.516 3.82e-08 ***
## age 1.047e-01 8.550e-03 12.249 < 2e-16 ***
## systolic 4.101e-03 2.091e-03 1.961 0.0500 *
## diastolic 6.455e-03 2.832e-03 2.279 0.0228 *
## weight 2.636e-02 1.221e-02 2.159 0.0310 *
## height -3.121e-02 1.214e-02 -2.571 0.0102 *
## bmi -7.503e-02 3.398e-02 -2.208 0.0274 *
## triglycerides 2.116e-02 1.620e-03 13.060 < 2e-16 ***
## I(triglycerides^2) -4.954e-05 4.948e-06 -10.011 < 2e-16 ***
## I(age^2) -1.105e-03 9.325e-05 -11.849 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.53 on 2493 degrees of freedom
## Multiple R-squared: 0.2085, Adjusted R-squared: 0.2057
## F-statistic: 72.98 on 9 and 2493 DF, p-value: < 2.2e-16
After model selection, we can find out that terms age, systolic, diastolic, weight, height, bmi, triglycerides, \(triglycerides^2\) and \(age^2\) are selected, and they are significant under t-test. The height bmi and the two square terms are negatively correlated with ldl, with other variables positively correlated with ldl. The residual standard error changes to 1.53, and the \(R^2\) increases to 0.2085, which means that this model performs better than the one without square terms.
* import demographic data
import sasxport "./Original Data/DEMO_I.XPT.txt", clear
* rename variables
rename riagendr gender
rename ridageyr age
rename ridreth3 race
* select variables of focus
keep seqn gender age race
* save the cleaned demographics data
save "./Xiru Lyu/Data/demo.dta", replace
* import diet (day 1) data
import sasxport "./Original Data/DR1TOT_I.XPT.txt", clear
* rename variables
rename dr1ttfat fat1
rename dr1tchol chol1
* select variables of interest
keep seqn fat1 chol1
* save the cleaned diet (day 1) dataset
save "./Xiru Lyu/Data/diet1.dta", replace
* import diet (day 2) data
import sasxport "./Original Data/DR2TOT_I.XPT.txt", clear
* rename variables
rename dr2ttfat fat2
rename dr2tchol chol2
* select variables of focus
keep seqn fat2 chol2
* save the cleaned diet (day 2) dataset
save "./Xiru Lyu/Data/diet2.dta", replace
* import LDL & triglyceride data
import sasxport "./Original Data/TRIGLY_I.XPT.txt", clear
* rename variables
rename lbdldl ldl
rename lbxtr triglyceride
* select variables of interest
keep seqn ldl trig
* save the cleaned cholesterol dataset
save "./Xiru Lyu/Data/ldl.dta", replace
* import blood pressure data
import sasxport "./Original Data/BPX_I.XPT.txt", clear
* rename variables
rename bpxsy1 sy1
rename bpxsy2 sy2
rename bpxsy3 sy3
rename bpxsy4 sy4
rename bpxdi1 di1
rename bpxdi2 di2
rename bpxdi3 di3
rename bpxdi4 di4
* compute averaged systolic and diastolic blood pressure for each participant
egen systolic = rowmean(sy1 sy2 sy3 sy4)
egen diastolic = rowmean(di1 di2 di3 di4)
* select variables of interest
keep seqn systolic diastolic
* save the cleaned blood pressure dataset
save "./Xiru Lyu/Data/bp.dta", replace
* import body measure data
import sasxport "./Original Data/BMX_I.XPT.txt", clear
* rename variables
rename bmxwt weight
rename bmxbmi bmi
rename bmxht height
* select variables of interest
keep seqn weight height bmi
* merge datasets by seqn
merge 1:1 seqn using "./Xiru Lyu/Data/demo.dta"
keep if _merge == 3
drop _merge
merge 1:1 seqn using "./Xiru Lyu/Data/diet1.dta"
keep if _merge == 3
drop _merge
merge 1:1 seqn using "./Xiru Lyu/Data/diet2.dta"
keep if _merge == 3
drop _merge
merge 1:1 seqn using "./Xiru Lyu/Data/bp.dta"
keep if _merge == 3
drop _merge
merge 1:1 seqn using "./Xiru Lyu/Data/ldl.dta"
keep if _merge == 3
drop _merge
* compute averaged intakes of fat and cholesterol
egen fat = rowmean(fat1 fat2)
egen chol = rowmean(chol1 chol2)
* drop extra columns
drop fat1 fat2 chol1 chol2
* drop rows with missing values
foreach var of varlist age bmi chol diastolic fat gender height ldl race ///
seqn systolic triglyceride weight{
drop if missing(`var')
}
* save the dataset for data analysis
save "./Xiru Lyu/Data/final.dta", replace
* transform the dependent variable
generate ldl2 = sqrt(ldl)
* fit a multiple linear regression model
regress ldl2 age i.race i.gender bmi weight height diastolic systolic chol ///
fat trig
Regression Result of Full Model (2)
I first fitted the full model, including all possible covariates and the transformed dependent variable, and then I used forward and backward stepwise selections for model selections. To be consistent with the result produced by R, I used the result from the backward selection for later AIC/BIC comparison.
* backward selection
xi: stepwise, pr(.1): regress ldl2 age i.race i.gender bmi weight height ///
diastolic systolic chol fat triglyceride
Backward Selection Result of Full Model (2)
* forward selection
xi: stepwise, pe(.1): regress ldl2 age i.race i.gender bmi weight height ///
diastolic systolioc chol fat triglyceride
Forward Selection Result of Full Model (2)
* transform covariates
generate triglyceride2 = triglyceride^2
generate age2 = age^2
* fit a multiple linear regression model
regress ldl2 age age2 i.race i.gender bmi weight height diastolic systolic ///
chol fat triglyceride triglyceride2
I then fitted another model that contains two extra transformed independent variables. With the stepwise model selection procedure, I kept the model selected by the backward selection as the one for further AIC/BIC comparison so that my result is consistent with the result produced by R.
Regression Result of Full Model (3)
* backward selection
xi: stepwise, pr(.05): regress ldl2 age age2 i.race i.gender bmi weight ///
height diastolic systolic chol fat triglyceride triglyceride2
Backward Selection Result of Full Model (3)
* forward selection
xi: stepwise, pe(.05): regress ldl2 age age2 i.race i.gender bmi weight ///
height diastolic systolic chol fat triglyceride triglyceride2
Forward Selection Result of Full Model (3)
* compare AIC & BIC of two nested models
regress ldl2 age height weight diastolic triglyceride
estat ic
AIC for Model 2_a
regress ldl2 age age2 height weight bmi diastolic systolic triglyceride ///
triglyceride2
estat ic
AIC for Model 2_b
A comparison for AIC/BIC for two nested models shows that the model \(\mathbf{\sqrt{LDL}}\) ~ \(\mathbf{age + age^2 + height + weight + BMI + triglyceride + triglyceride^2 + diastolic + systolic}\) is the better one. Inferential statistics for the model is produced below. Covariates age, triglyceride, weight, diastolic and systolic blood pressures are positively correlated with the level of LDL, while \(age^2\), \(triglyceride^2\) and BMI are negatively correlated with the response variable.
Specifically, with other variables fixed, one year increase in age leads to approximately 0.10 unit of increase in \(\sqrt{ldl}\). Also, the rate of increase for the level of \(\sqrt{ldl}\) slows down as one ages. One unit of increase in diastolic blood pressure can increase \(\sqrt{ldl}\) by 0.006 unit. One unit of increase in systolic blood pressure can increase \(\sqrt{ldl}\) by 0.004 unit. One unit of increase in BMI decreases \(\sqrt{ldl}\) by 0.075 unit. One unit of increase in weight and triglyceride can bump up \(\sqrt{ldl}\) by .026 and .021 unit, respectively. Finally, one unit increase in height leads to approximately 0.026 unit of decrease in \(\sqrt{ldl}\).
Note for Python, we use pandas to merge and clean all datasets. Because there is no package to perform stepwise model selection, so we refer outsource codes from the internet for stepwise selection by AIC. Links for reference are attached to code chunks below.
import pandas as pd
import numpy as np
LDLdata=pd.read_sas(r'./Original Data/TRIGLY_I.XPT',encoding='utf8')
DR1=pd.read_sas(r'./Original Data/DR1TOT_I.XPT',encoding='utf8')
DR2=pd.read_sas(r'./Original Data/DR2TOT_I.XPT',encoding='utf8')
BPX=pd.read_sas(r'./Original Data/BPX_I.XPT',encoding='utf8')
DEMO=pd.read_sas(r'./Original Data/DEMO_I.XPT',encoding='utf8')
BMI=pd.read_sas(r'./Original Data/BMX_I.XPT',encoding='utf8')
LDL=LDLdata[['SEQN','LBXTR', 'LBDLDL']]#select cols
#WTSAF2YR:MEC weight
#LBXTR: triglyceride(mg/dl)
#LBDLDL: LDL mg/dl
BloodP=BPX[['SEQN']]
BloodP['BPXSY']=np.nanmean(BPX[['BPXSY1','BPXSY2','BPXSY3','BPXSY4']],axis=1)#mean value omitting na value
## /Users/lihuayu/anaconda3/bin/python:1: RuntimeWarning: Mean of empty slice
## /Users/lihuayu/anaconda3/bin/python:1: SettingWithCopyWarning:
## A value is trying to be set on a copy of a slice from a DataFrame.
## Try using .loc[row_indexer,col_indexer] = value instead
##
## See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
BloodP['BPXDI']=np.nanmean(BPX[['BPXDI1','BPXDI2','BPXDI3','BPXDI4']],axis=1)
drday1=DR1[['SEQN','DR1TTFAT','DR1TCHOL']] #select cols
drday2=DR2[['SEQN','DR2TTFAT','DR2TCHOL']]
drboth=pd.merge(drday1,drday2,how='inner',on='SEQN')#merge table
drboth['FAT']=np.nanmean(drboth[['DR1TTFAT','DR2TTFAT']],axis=1)
drboth['CHOL']=np.nanmean(drboth[['DR1TCHOL','DR2TCHOL']],axis=1)
dr=drboth[['SEQN','FAT','CHOL']]
demo=DEMO[['SEQN','RIAGENDR','RIDAGEYR','RIDRETH3']]
#ID,GENDER,AGE,RACE(FACTOR)
demo.rename(columns={'RIAGENDR':'GENDER','RIDAGEYR':'AGE','RIDRETH3':'RACE'},inplace=True)#rename colnames
## /Users/lihuayu/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py:4025: SettingWithCopyWarning:
## A value is trying to be set on a copy of a slice from a DataFrame
##
## See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
## return super(DataFrame, self).rename(**kwargs)
BMI=BMI[['SEQN','BMXHT','BMXWT','BMXBMI']]
#ID,HEIGHT,WEIGHT
BMI.columns=['SEQN','HEIGHT','WEIGHT','BMI']
#merge tables
Data=pd.merge(LDL,BloodP,how='inner',on='SEQN')
Data=pd.merge(Data,dr,how='inner',on='SEQN')
Data=pd.merge(Data,demo,how='inner',on='SEQN')
Data=pd.merge(Data,BMI,how='inner',on='SEQN')
Data=Data.dropna(axis=0)
Data.to_csv(r'Data1.csv',index=None)
#save table
import pandas as pd
import numpy as np
from sklearn import linear_model
from scipy import stats
import statsmodels.formula.api as smf
import matplotlib.pyplot as plt
import pylab
import statsmodels.api as sm
Data=pd.read_csv(r'Data1.csv')#read table
Data=Data.drop(['SEQN'],axis=1)#drop the id variable 'SEQN'
#python seems has no direct code to deal factor variables like R
RACE=pd.get_dummies(Data['RACE'])
RACENAME=['Mexican American','Other Hispanic','Non-Hispanic White','Non-Hispanic Black','Non-Hispanic Asian','Other Race']
RACE.columns=[ i for i in RACENAME]
RACE=RACE.drop(['Mexican American'],axis=1)
GENDER=pd.get_dummies(Data['GENDER'])
gendername=['Male','Female']
GENDER.columns=[i for i in gendername]
GENDER=GENDER.drop(['Male'],axis=1)
Data=Data.drop(['GENDER','RACE'],axis=1)
Data=pd.concat([Data,GENDER,RACE],axis=1)
y1=Data[['LBDLDL']] ## lm reg, the response= LBDLDL (LDL)
x1=Data.drop(['LBDLDL'],axis=1) # others except LDL are the variables
x1=sm.add_constant(x1) ## add intercept, for python, add 1 colunms by hand
## /Users/lihuayu/anaconda3/lib/python3.7/site-packages/numpy/core/fromnumeric.py:2495: FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead.
## return ptp(axis=axis, out=out, **kwargs)
lm1=sm.OLS(y1.astype(float),x1.astype(float)).fit() # OLS y on X+1
lm1.summary() # coefficient table
## <class 'statsmodels.iolib.summary.Summary'>
## """
## OLS Regression Results
## ==============================================================================
## Dep. Variable: LBDLDL R-squared: 0.134
## Model: OLS Adj. R-squared: 0.129
## Method: Least Squares F-statistic: 25.69
## Date: Thu, 12 Dec 2019 Prob (F-statistic): 2.47e-67
## Time: 14:40:07 Log-Likelihood: -12321.
## No. Observations: 2503 AIC: 2.467e+04
## Df Residuals: 2487 BIC: 2.477e+04
## Df Model: 15
## Covariance Type: nonrobust
## ======================================================================================
## coef std err t P>|t| [0.025 0.975]
## --------------------------------------------------------------------------------------
## const 101.5715 44.874 2.263 0.024 13.576 189.566
## LBXTR 0.1428 0.011 12.546 0.000 0.120 0.165
## BPXSY -0.0059 0.046 -0.129 0.898 -0.096 0.084
## BPXDI 0.4018 0.057 6.994 0.000 0.289 0.514
## FAT 0.0053 0.023 0.233 0.816 -0.039 0.050
## CHOL -0.0013 0.004 -0.288 0.774 -0.010 0.007
## AGE 0.1758 0.039 4.544 0.000 0.100 0.252
## HEIGHT -0.3181 0.270 -1.180 0.238 -0.847 0.211
## WEIGHT 0.3017 0.266 1.133 0.257 -0.220 0.824
## BMI -0.5955 0.741 -0.803 0.422 -2.049 0.858
## Female 1.1712 1.848 0.634 0.526 -2.452 4.794
## Other Hispanic 3.9526 2.414 1.637 0.102 -0.781 8.687
## Non-Hispanic White 2.0370 2.094 0.973 0.331 -2.069 6.143
## Non-Hispanic Black 3.5060 2.286 1.534 0.125 -0.977 7.989
## Non-Hispanic Asian 5.1046 2.738 1.864 0.062 -0.265 10.474
## Other Race 6.0369 3.880 1.556 0.120 -1.572 13.646
## ==============================================================================
## Omnibus: 121.293 Durbin-Watson: 1.991
## Prob(Omnibus): 0.000 Jarque-Bera (JB): 161.325
## Skew: 0.469 Prob(JB): 9.30e-36
## Kurtosis: 3.816 Cond. No. 2.87e+04
## ==============================================================================
##
## Warnings:
## [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
## [2] The condition number is large, 2.87e+04. This might indicate that there are
## strong multicollinearity or other numerical problems.
## """
#plot residual vesus y-fitted
res1=lm1.resid
y1_fit=lm1.predict(x1)
fig1=plt.figure(figsize=(8,6))
plt.plot(y1_fit,res1,'o''c') #'0' means dots,''''means no line between dots, 'c' color
plt.title('Residuals against Y-fited')
plt.ylabel('Residuals')
plt.xlabel('Y-fitted value')
plt.show()
res = lm1.resid # residuals
stats.probplot(res, dist="norm", plot=pylab) # QQplot, simliar to fig = sm.qqplot(res)
pylab.show()
Probability Plot
First, we graph the QQ-plot of residuals, and we can see errors deviate a bit from the normality assumption.
# boxcox
y2=np.array(y1).flatten() #get pandas col as list(like vector in R)
fig2=plt.figure()
ax = fig2.add_subplot(111)
#plot boxcox
prob=stats.boxcox_normplot(y2,0,1,plot=ax)
_, maxlog=stats.boxcox(y2)
ax.axvline(maxlog,color='r')
## <matplotlib.lines.Line2D object at 0x14511acc0>
plt.show()
From the plot, we can transform the response to \(y^\lambda\), and the result seems the best when lambda is around 0.4. For simplicity, we pick \(\lambda=0.5\).
Data['LDL']=(Data[['LBDLDL']])**0.5 # transform the y value to y**0.5 as picked
Data=Data.drop(['LBDLDL'],axis=1)
y3=Data[['LDL']]
x3=Data.drop(['LDL'],axis=1)
#select model
final_vars,_=forwardSelection(x3,y3,model_type='linear',elimination_criteria='aic')
## Character Variables (Dummies Generated, First Dummies Dropped): []
## Entered : LBXTR AIC : 9574.218891776083
## Entered : BPXDI AIC : 9503.117731043025
## Entered : AGE AIC : 9475.727581279705
## Entered : BMI AIC : 9470.123755541823
## Break : Significance Level
## OLS Regression Results
## ==============================================================================
## Dep. Variable: LDL R-squared: 0.130
## Model: OLS Adj. R-squared: 0.128
## Method: Least Squares F-statistic: 93.04
## Date: Thu, 12 Dec 2019 Prob (F-statistic): 7.62e-74
## Time: 14:40:08 Log-Likelihood: -4730.1
## No. Observations: 2503 AIC: 9470.
## Df Residuals: 2498 BIC: 9499.
## Df Model: 4
## Covariance Type: nonrobust
## ==============================================================================
## coef std err t P>|t| [0.025 0.975]
## ------------------------------------------------------------------------------
## intercept 7.4982 0.199 37.641 0.000 7.108 7.889
## LBXTR 0.0065 0.001 12.356 0.000 0.005 0.008
## BPXDI 0.0199 0.003 7.769 0.000 0.015 0.025
## AGE 0.0081 0.002 5.007 0.000 0.005 0.011
## BMI 0.0130 0.005 2.757 0.006 0.004 0.022
## ==============================================================================
## Omnibus: 8.993 Durbin-Watson: 1.996
## Prob(Omnibus): 0.011 Jarque-Bera (JB): 11.361
## Skew: -0.017 Prob(JB): 0.00341
## Kurtosis: 3.328 Cond. No. 895.
## ==============================================================================
##
## Warnings:
## [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
## AIC: 9470.123755541823
## BIC: 9499.249981998983
## Final Variables: ['intercept', 'LBXTR', 'BPXDI', 'AGE', 'BMI']
final_vars,_=backwardSelection(x3,y3,model_type='linear',elimination_criteria='aic')
## Character Variables (Dummies Generated, First Dummies Dropped): []
## Eliminated : BPXSY
## Eliminated : FAT
## Eliminated : CHOL
## Eliminated : Female
## Eliminated : BMI
## Eliminated : Non-Hispanic White
## Eliminated : Non-Hispanic Black
## Eliminated : Other Hispanic
## Eliminated : Other Race
## Eliminated : Non-Hispanic Asian
## OLS Regression Results
## ==============================================================================
## Dep. Variable: LDL R-squared: 0.130
## Model: OLS Adj. R-squared: 0.129
## Method: Least Squares F-statistic: 74.87
## Date: Thu, 12 Dec 2019 Prob (F-statistic): 2.88e-73
## Time: 14:40:09 Log-Likelihood: -4729.0
## No. Observations: 2503 AIC: 9470.
## Df Residuals: 2497 BIC: 9505.
## Df Model: 5
## Covariance Type: nonrobust
## ==============================================================================
## coef std err t P>|t| [0.025 0.975]
## ------------------------------------------------------------------------------
## intercept 8.8489 0.577 15.332 0.000 7.717 9.981
## LBXTR 0.0065 0.001 12.306 0.000 0.005 0.008
## BPXDI 0.0203 0.003 7.847 0.000 0.015 0.025
## AGE 0.0080 0.002 4.978 0.000 0.005 0.011
## HEIGHT -0.0084 0.004 -2.301 0.021 -0.016 -0.001
## WEIGHT 0.0049 0.002 2.886 0.004 0.002 0.008
## ==============================================================================
## Omnibus: 8.921 Durbin-Watson: 1.994
## Prob(Omnibus): 0.012 Jarque-Bera (JB): 11.283
## Skew: -0.012 Prob(JB): 0.00355
## Kurtosis: 3.328 Cond. No. 4.12e+03
## ==============================================================================
##
## Warnings:
## [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
## [2] The condition number is large, 4.12e+03. This might indicate that there are
## strong multicollinearity or other numerical problems.
## AIC: 9470.09711553212
## BIC: 9505.048587280711
## Final Variables: ['intercept', 'LBXTR', 'BPXDI', 'AGE', 'HEIGHT', 'WEIGHT']
From graphs above, we can see that in LBXTR and AGE plots, there is a little inverse ‘U’ shape. Thus, in the final model, we add \(LBXTR^2\) and \(AGE^2\) terms.
Data['AGE2']=Data[['AGE']]*Data[['AGE']]
Data['LBXTR2']=Data[['LBXTR']]*Data[['LBXTR']]
y5=Data[['LDL']]
x5=Data.drop(['LDL'],axis=1)
#add new variables and reslect model
final_vars,_=forwardSelection(x5,y5,model_type='linear',elimination_criteria='aic')
## Character Variables (Dummies Generated, First Dummies Dropped): []
## Entered : LBXTR AIC : 9574.218891776083
## Entered : LBXTR2 AIC : 9448.966446031709
## Entered : BPXDI AIC : 9384.22136728393
## Entered : AGE AIC : 9373.946948986257
## Entered : AGE2 AIC : 9246.164944091768
## Break : Significance Level
## OLS Regression Results
## ==============================================================================
## Dep. Variable: LDL R-squared: 0.205
## Model: OLS Adj. R-squared: 0.203
## Method: Least Squares F-statistic: 128.6
## Date: Thu, 12 Dec 2019 Prob (F-statistic): 1.75e-121
## Time: 14:40:10 Log-Likelihood: -4617.1
## No. Observations: 2503 AIC: 9246.
## Df Residuals: 2497 BIC: 9281.
## Df Model: 5
## Covariance Type: nonrobust
## ==============================================================================
## coef std err t P>|t| [0.025 0.975]
## ------------------------------------------------------------------------------
## intercept 6.2939 0.195 32.322 0.000 5.912 6.676
## LBXTR 0.0213 0.002 13.348 0.000 0.018 0.024
## LBXTR2 -4.949e-05 4.9e-06 -10.094 0.000 -5.91e-05 -3.99e-05
## BPXDI 0.0078 0.003 2.971 0.003 0.003 0.013
## AGE 0.1004 0.008 11.994 0.000 0.084 0.117
## AGE2 -0.0010 9.04e-05 -11.528 0.000 -0.001 -0.001
## ==============================================================================
## Omnibus: 8.099 Durbin-Watson: 1.962
## Prob(Omnibus): 0.017 Jarque-Bera (JB): 9.982
## Skew: -0.024 Prob(JB): 0.00680
## Kurtosis: 3.306 Cond. No. 1.60e+05
## ==============================================================================
##
## Warnings:
## [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
## [2] The condition number is large, 1.6e+05. This might indicate that there are
## strong multicollinearity or other numerical problems.
## AIC: 9246.164944091768
## BIC: 9281.116415840359
## Final Variables: ['intercept', 'LBXTR', 'LBXTR2', 'BPXDI', 'AGE', 'AGE2']
final_vars,_=backwardSelection(x5,y5,model_type='linear',elimination_criteria='aic')
## Character Variables (Dummies Generated, First Dummies Dropped): []
## Eliminated : FAT
## Eliminated : Other Hispanic
## Eliminated : Non-Hispanic Asian
## Eliminated : Female
## Eliminated : CHOL
## Eliminated : Non-Hispanic White
## Regained : Non-Hispanic White
## OLS Regression Results
## ==============================================================================
## Dep. Variable: LDL R-squared: 0.210
## Model: OLS Adj. R-squared: 0.207
## Method: Least Squares F-statistic: 55.30
## Date: Thu, 12 Dec 2019 Prob (F-statistic): 1.87e-118
## Time: 14:40:10 Log-Likelihood: -4608.2
## No. Observations: 2503 AIC: 9242.
## Df Residuals: 2490 BIC: 9318.
## Df Model: 12
## Covariance Type: nonrobust
## ======================================================================================
## coef std err t P>|t| [0.025 0.975]
## --------------------------------------------------------------------------------------
## intercept 11.3355 2.013 5.631 0.000 7.388 15.283
## LBXTR 0.0216 0.002 13.060 0.000 0.018 0.025
## BPXSY 0.0040 0.002 1.881 0.060 -0.000 0.008
## BPXDI 0.0065 0.003 2.279 0.023 0.001 0.012
## AGE 0.1063 0.009 12.338 0.000 0.089 0.123
## HEIGHT -0.0333 0.012 -2.731 0.006 -0.057 -0.009
## WEIGHT 0.0262 0.012 2.143 0.032 0.002 0.050
## BMI -0.0757 0.034 -2.228 0.026 -0.142 -0.009
## Non-Hispanic White 0.1253 0.075 1.667 0.096 -0.022 0.273
## Non-Hispanic Black 0.1642 0.088 1.876 0.061 -0.007 0.336
## Other Race 0.2850 0.167 1.702 0.089 -0.043 0.613
## AGE2 -0.0011 9.45e-05 -11.900 0.000 -0.001 -0.001
## LBXTR2 -5.047e-05 5e-06 -10.099 0.000 -6.03e-05 -4.07e-05
## ==============================================================================
## Omnibus: 7.701 Durbin-Watson: 1.963
## Prob(Omnibus): 0.021 Jarque-Bera (JB): 9.303
## Skew: -0.034 Prob(JB): 0.00955
## Kurtosis: 3.291 Cond. No. 1.66e+06
## ==============================================================================
##
## Warnings:
## [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
## [2] The condition number is large, 1.66e+06. This might indicate that there are
## strong multicollinearity or other numerical problems.
## AIC: 9242.336445749102
## BIC: 9318.064634537715
## Final Variables: ['intercept', 'LBXTR', 'BPXSY', 'BPXDI', 'AGE', 'HEIGHT', 'WEIGHT', 'BMI', 'Non-Hispanic White', 'Non-Hispanic Black', 'Other Race', 'AGE2', 'LBXTR2']
From model selection by AIC, we select variables ‘LBXTR’, ‘BPXSY’, ‘BPXDI’, ‘AGE’, ‘HEIGHT’, ‘WEIGHT’, ‘BMI’, ‘RACE’, ‘AGE2’, ‘LBXTR2’
#part of race as selected, it is little strange to put part varibles in, so I put all the race varaibles in the final model, and my model may little differ from my groups
y=Data[['LDL']]
x=Data[['LBXTR', 'BPXSY', 'BPXDI', 'AGE', 'HEIGHT', 'WEIGHT', 'BMI','Other Hispanic','Non-Hispanic White','Non-Hispanic Black','Non-Hispanic Asian','Other Race', 'AGE2', 'LBXTR2']]
#here we add all RACE types except RACE='Mexican American', which is viewed as base
#reg and see final selected model coeffs
x=sm.add_constant(x)
## /Users/lihuayu/anaconda3/lib/python3.7/site-packages/numpy/core/fromnumeric.py:2495: FutureWarning: Method .ptp is deprecated and will be removed in a future version. Use numpy.ptp instead.
## return ptp(axis=axis, out=out, **kwargs)
lm_final=sm.OLS(y.astype(float),x.astype(float)).fit()
lm_final.summary()
## <class 'statsmodels.iolib.summary.Summary'>
## """
## OLS Regression Results
## ==============================================================================
## Dep. Variable: LDL R-squared: 0.211
## Model: OLS Adj. R-squared: 0.206
## Method: Least Squares F-statistic: 47.49
## Date: Thu, 12 Dec 2019 Prob (F-statistic): 5.38e-117
## Time: 14:40:10 Log-Likelihood: -4607.5
## No. Observations: 2503 AIC: 9245.
## Df Residuals: 2488 BIC: 9332.
## Df Model: 14
## Covariance Type: nonrobust
## ======================================================================================
## coef std err t P>|t| [0.025 0.975]
## --------------------------------------------------------------------------------------
## const 11.1998 2.017 5.552 0.000 7.244 15.155
## LBXTR 0.0216 0.002 13.012 0.000 0.018 0.025
## BPXSY 0.0041 0.002 1.922 0.055 -8.27e-05 0.008
## BPXDI 0.0063 0.003 2.212 0.027 0.001 0.012
## AGE 0.1057 0.009 12.245 0.000 0.089 0.123
## HEIGHT -0.0329 0.012 -2.700 0.007 -0.057 -0.009
## WEIGHT 0.0256 0.012 2.100 0.036 0.002 0.050
## BMI -0.0732 0.034 -2.150 0.032 -0.140 -0.006
## Other Hispanic 0.0896 0.111 0.810 0.418 -0.127 0.307
## Non-Hispanic White 0.1879 0.094 1.997 0.046 0.003 0.372
## Non-Hispanic Black 0.2247 0.103 2.175 0.030 0.022 0.427
## Non-Hispanic Asian 0.1355 0.125 1.081 0.280 -0.110 0.381
## Other Race 0.3472 0.177 1.966 0.049 0.001 0.694
## AGE2 -0.0011 9.46e-05 -11.824 0.000 -0.001 -0.001
## LBXTR2 -5.029e-05 5e-06 -10.053 0.000 -6.01e-05 -4.05e-05
## ==============================================================================
## Omnibus: 7.784 Durbin-Watson: 1.965
## Prob(Omnibus): 0.020 Jarque-Bera (JB): 9.359
## Skew: -0.038 Prob(JB): 0.00928
## Kurtosis: 3.290 Cond. No. 1.66e+06
## ==============================================================================
##
## Warnings:
## [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
## [2] The condition number is large, 1.66e+06. This might indicate that there are
## strong multicollinearity or other numerical problems.
## """
## Additional Analysis: Some extra graphs
## Libraries: -------------------------------------------------------------------------
library(ggplot2)
library(gridExtra)
## 80: --------------------------------------------------------------------------------
## Graph 1: Some Diagnosis upon these models
### F1: Checking error assumptions--residual plots
R1=data.table(fitted_values=L2$fitted.values,residuals=L2$residuals)
R2=data.table(fitted_values=L3$fitted.values,residuals=L3$residuals)
R3=data.table(fitted_values=L4$fitted.values,residuals=L4$residuals)
R4=data.table(fitted_values=L5$fitted.values,residuals=L5$residuals)
rs1=ggplot(R1,aes(x=fitted_values,y=residuals))+geom_point(size=1,colour='blue')+
labs(title='Model 1')
rs2=ggplot(R2,aes(x=fitted_values,y=residuals))+geom_point(size=1,colour='blue')+
labs(title='Model 2')
rs3=ggplot(R3,aes(x=fitted_values,y=residuals))+geom_point(size=1,colour='blue')+
labs(title='Model 3')
rs4=ggplot(R4,aes(x=fitted_values,y=residuals))+geom_point(size=1,colour='blue')+
labs(title='Model 4')
grid.arrange(rs1,rs2,rs3,rs4,nrow=2)
## Graph 2: QQ-plots of the models
par(mfrow=c(2,2))
qqnorm(R1$residuals, ylab="Residuals",main='Q-Q Plot of Model 1')
qqline(R1$residuals)
qqnorm(R2$residuals, ylab="Residuals",main='Q-Q Plot of Model 2')
qqline(R2$residuals)
qqnorm(R3$residuals, ylab="Residuals",main='Q-Q Plot of Model 3')
qqline(R3$residuals)
qqnorm(R4$residuals, ylab="Residuals",main='Q-Q Plot of Model 4')
qqline(R4$residuals)
## Graph 3: Partial Residual Plots upon Model 3 and 4
crPlots(L4,layout=c(3,3))
crPlots(L5)
## Graph 4: Relationships between ldl and gender/race. We have the mean level of
## ldl between different gender and race (For CI, we will use the JackKnife
## standard error.)
Mean_JK = function(x){
lx=length(x)
MX=matrix(rep(x,rep(lx-1,lx)),ncol=lx,byrow=TRUE)
theta=colMeans(MX)
mean_theta=mean(theta)
std_theta={(lx-1)/lx*sum((theta-mean_theta)^2)}^(1/2)
std_theta
}
Gend=DT[,.(gender,ldl)]
Race=DT[,.(race,ldl)]
MG=Gend[,.(mean_ldl=mean(ldl),l_ldl=mean(ldl)+qnorm(0.025)*Mean_JK(ldl),
r_ldl=mean(ldl)+qnorm(0.975)*Mean_JK(ldl)),by=gender]
MR=Race[,.(mean_ldl=mean(ldl),l_ldl=mean(ldl)+qnorm(0.025)*Mean_JK(ldl),
r_ldl=mean(ldl)+qnorm(0.975)*Mean_JK(ldl)),by=race]
gend=ggplot(Gend,aes(x=gender,y=ldl))+geom_point(size=1,colour='blue')+
labs(title='ldl~gender')
race=ggplot(Race,aes(x=race,y=ldl))+geom_point(size=1,colour='blue')+
labs(title='ldl~race')
mean_gend=ggplot(MG,aes(x=gender,y=mean_ldl))+geom_point(shape=16,col='red')+
geom_segment(data=MG,mapping=aes(x=gender,xend=gender,y=l_ldl,yend=r_ldl),
col='blue')+
labs(title = 'Mean level of ldl between genders')
mean_race=ggplot(MR,aes(x=race,y=mean_ldl))+geom_point(shape=16,col='red')+
geom_segment(data=MR,mapping=aes(x=race,xend=race,y=l_ldl,yend=r_ldl),
col='blue')+
labs(title = 'Mean level of ldl between races')
grid.arrange(gend,race,mean_gend,mean_race,nrow=2)
Here we plot residual plots and QQ-plots, and the result shows that the fitted model satisfies assumptions for the OLS model. In addition, we plot relationships between ldl and gender and race, and plots show that the ldl level of males is slightly higher than females, when fixing other variables. For race, the ldl level of Other Race is the highest from the whole, and for Non-Hispanic Black is the lowest.
## Before graphing, we will have the linear mixed model upon the dataset:
LM=lmer(ldl~age+intake_fat+intake_chol+systolic+diastolic+
weight+height+bmi+triglycerides+(1|gender)+(1|race),data=DT)
summary(LM)
## Linear mixed model fit by REML ['lmerMod']
## Formula: ldl ~ age + intake_fat + intake_chol + systolic + diastolic +
## weight + height + bmi + triglycerides + (1 | gender) + (1 | race)
## Data: DT
##
## REML criterion at convergence: 24691.1
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -3.3525 -0.6773 -0.0739 0.5917 4.4911
##
## Random effects:
## Groups Name Variance Std.Dev.
## race (Intercept) 0.695 0.8337
## gender (Intercept) 0.000 0.0000
## Residual 1111.545 33.3398
## Number of obs: 2503, groups: race, 6; gender, 2
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 111.161885 43.863459 2.534
## age 0.175052 0.038036 4.602
## intake_fat 0.001994 0.022497 0.089
## intake_chol -0.001512 0.004350 -0.348
## systolic -0.009931 0.045057 -0.220
## diastolic 0.411477 0.056723 7.254
## weight 0.309732 0.265604 1.166
## height -0.351071 0.264700 -1.326
## bmi -0.630334 0.737863 -0.854
## triglycerides 0.141182 0.011105 12.714
##
## Correlation of Fixed Effects:
## (Intr) age intk_f intk_c systlc distlc weight height bmi
## age 0.073
## intake_fat 0.047 0.053
## intake_chol -0.011 -0.066 -0.596
## systolic -0.074 -0.458 0.027 0.015
## diastolic 0.011 0.102 -0.063 0.033 -0.302
## weight 0.961 0.071 0.017 -0.012 -0.009 0.022
## height -0.992 -0.054 -0.071 0.009 -0.003 -0.051 -0.963
## bmi -0.957 -0.081 -0.016 0.004 -0.003 -0.040 -0.991 0.955
## triglycerds -0.073 -0.134 0.053 -0.039 -0.047 -0.081 -0.093 0.077 0.067
## convergence code: 0
## boundary (singular) fit: see ?isSingular
Addutionally, I fitted a mixed effect model, having gender and race as random intercepts. The amount of variation explained by these two effects is roughly 0.006%, implying that the linear mixed model doesn’t work well.
I am interested in exploring the specific relationship between the level of triglyceride and the response varaiable \(\sqrt{ldl}\). In partcular, does the relationship varies with the specific quantile of triglyceride? I used quantile regression to find the answer.
qreg ldl2 triglyceride, quantile(0.05)
qreg ldl2 triglyceride, quantile(0.25)
qreg ldl2 triglyceride, quantile(0.5)
qreg ldl2 triglyceride, quantile(0.75)
qreg ldl2 triglyceride, quantile(0.90)
Quantile Regression Results
Quantile Regression Plot
The quantile plot above shows that the level of triglyceride has positive correlation with the \(\sqrt{ldl}\) and the relationship between the two doesn’t vary much by quantile. Also, note that the quantile plot is generated with R and a detailed script is located under the folder /Xiru Lyu/quantile.R.
# additional analysis
#quantile regression: sqrt(LDL)~AGE
mod=smf.quantreg('LDL~AGE',Data)
quantiles = np.arange(.05, .95, .1)#ser quantile level
def fit_model(q): #def a quantile regression function
res = mod.fit(q=q)
return [q, res.params['Intercept'], res.params['AGE']] + \
res.conf_int().loc['AGE'].tolist()
models = [fit_model(x) for x in quantiles]
#set columns for quantile interception slope CI(lower_bound,up_bound)
models = pd.DataFrame(models, columns=['q', 'a', 'b', 'lower_b', 'upper_b'])
ols = smf.ols('LDL ~ AGE', Data).fit() #normal reg
ols_ci = ols.conf_int().loc['AGE'].tolist()
ols = dict(a = ols.params['Intercept'],
b = ols.params['AGE'],
lower_b = ols_ci[0], # Ci for b,lowerbound
upper_b = ols_ci[1]) #CI for b, upbound
print(models)
#plot quantile fig line by line
## q a b lower_b upper_b
## 0 0.05 7.365460 0.003383 -0.004561 0.011326
## 1 0.15 8.134052 0.008011 0.003168 0.012855
## 2 0.25 8.476658 0.013114 0.008268 0.017960
## 3 0.35 8.848354 0.016674 0.012116 0.021231
## 4 0.45 9.222907 0.017595 0.013548 0.021642
## 5 0.55 9.687246 0.016327 0.012471 0.020183
## 6 0.65 9.993639 0.019470 0.015664 0.023275
## 7 0.75 10.422161 0.020762 0.016958 0.024566
## 8 0.85 11.041352 0.020834 0.016755 0.024912
x = np.arange(Data.AGE.min(), Data.AGE.max()+1, 1)
get_y = lambda a, b: a + b * x
fig, ax = plt.subplots(figsize=(8, 6))
y = get_y(models.a[0], models.b[0])
ax.plot(x, y, linestyle='dotted', color='c',label='tau=0.05')
## [<matplotlib.lines.Line2D object at 0x1450c69e8>]
y = get_y(models.a[1], models.b[1])
ax.plot(x, y, linestyle='dotted', color='g',label='tau=0.15')
## [<matplotlib.lines.Line2D object at 0x1450ec630>]
y = get_y(models.a[2], models.b[2])
ax.plot(x, y, linestyle='dotted', color='b',label='tau=0.25')
## [<matplotlib.lines.Line2D object at 0x1450ec278>]
y = get_y(models.a[3], models.b[3])
ax.plot(x, y, linestyle='dotted', color='c',label='tau=0.35')
## [<matplotlib.lines.Line2D object at 0x1450aef98>]
y = get_y(models.a[4], models.b[4])
ax.plot(x, y, linestyle='dotted', color='g',label='tau=0.45')
## [<matplotlib.lines.Line2D object at 0x1450ae5c0>]
y = get_y(models.a[5], models.b[5])
ax.plot(x, y, linestyle='dotted', color='b',label='tau=0.55')
## [<matplotlib.lines.Line2D object at 0x1450ae710>]
y = get_y(models.a[6], models.b[6])
ax.plot(x, y, linestyle='dotted', color='c',label='tau=0.65')
## [<matplotlib.lines.Line2D object at 0x1450ae278>]
y = get_y(models.a[7], models.b[7])
ax.plot(x, y, linestyle='dotted', color='g',label='tau=0.75')
## [<matplotlib.lines.Line2D object at 0x1455108d0>]
y = get_y(models.a[8], models.b[8])
ax.plot(x, y, linestyle='dotted', color='b',label='tau=0.85')
## [<matplotlib.lines.Line2D object at 0x1161654e0>]
y = get_y(ols['a'], ols['b'])
ax.plot(x, y, color='red', label='OLS')
## [<matplotlib.lines.Line2D object at 0x1450ec908>]
ax.scatter(Data.AGE, Data.LDL, alpha=.2)
## <matplotlib.collections.PathCollection object at 0x145510390>
ax.set_xlim((10, 85))
## (10, 85)
ax.set_ylim((3.0, 17.5))
## (3.0, 17.5)
legend = ax.legend()
ax.set_xlabel('AGE', fontsize=16)
## Text(0.5, 0, 'AGE')
ax.set_ylabel('LDL(sqrt_LDL)', fontsize=16);
## Text(0, 0.5, 'LDL(sqrt_LDL)')
plt.show()
I would like to see if there is any specific relationship between the level of LDL and age. As demonstrated by the plot of the quantile regression, regression lines for different quantiles are roughly parallel, suggesting that the variance of the response variable is constant across values of age.
All of the three tools above use the stepwise model selection technique to choose the best fitted model, but there are some differences existing among these tools.
For the tool using data.table in R, the model selection function is just as step(,direction=''), and the direction choose is both; note that the selection criterion is by AIC. For Stata, the model selection technique is performed using stepwise, and the selection criterion is based on p-values. As Stata cannot perform the stepwise selection in both directions, separate forward and backward selections are performed, and p-values are tuned so that model selection results match those by R. For Python, the code for backward and forward selections are downloaded from the given Github site, and the selection criteria is by AIC. As the model selection technique differs for Python in selecting categorical variables of multiple levels, the final regression results by Python are slightly different from those by R and Stata.
To conclude, age, systolic, diastolic, weight, height, bmi, triglycerides, \(triglyceride^2\), \(age^2\) are significant predictors that affect the level of ldl. Specifically, age, systolic, diastolic,weight and triglycerides have positive correlations with the response, while height and bmi have negative relationships. For triglyceride and age, as they increase, the rate of increase for \(\sqrt{ldl}\) becomes slowly.